﻿using System;
using System.Drawing;
using System.Web.Configuration;
using TTprotons.Crm.ExternalView.Service.Common;
using TTprotons.Crm.ExternalView.Service.Crm;
using TTprotons.Crm.ExternalView.Service.Settings;

namespace TTprotons.Crm.ExternalView.Service
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Set Configuration Panel visibility
                SetConfigurationPanelVisibility();
            }
        }

        private void SetConfigurationPanelVisibility()
        {
            var isConfigured = !Config.CrmOnlineOrganization.IsNullOrEmpty() &&
                               !Config.CrmOnlineUserId.IsNullOrEmpty() &&
                               !Config.CrmOnlinePassword.IsNullOrEmpty();

            uxConfiguration.Visible = !isConfigured;
        }

        protected void uxValidate_Click(object sender, EventArgs e)
        {
            var queryManager = new CrmOnlineQueryManager();
            var result = queryManager.Connect(uxUsername.Text, uxPassword.Text, uxOrganisation.Text);

            if (result.IsSuccess)
            {
                var theConfig = WebConfigurationManager.OpenWebConfiguration("~");
                theConfig.AppSettings.Settings["CrmOnlineUserId"].Value = uxUsername.Text;
                theConfig.AppSettings.Settings["CrmOnlinePassword"].Value = uxPassword.Text;
                theConfig.AppSettings.Settings["CrmOnlineOrganization"].Value = uxOrganisation.Text;
                theConfig.Save();

                uxMessage.Text = "Setting saved";
                uxMessage.ForeColor = Color.Blue;
            }
            else
            {
                // Display error message.
                uxMessage.Text = "Unable to connect to CRM Online. Please try again.";
                uxMessage.ForeColor = Color.Red;
            }
        }
    }
}